from cdsay.upfile.form import PictureForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from cdsay.upfile.models import saveFileModel

def addPicture(request):  
    if request.method == 'POST':  
        data=request.FILES['file']
        #
        #print data
        filename = "C:/JHL/WorkSpace/test.txt"
        
        arq = open(filename, 'wb')
        arq.write(data.read())
        arq.close()
        
        fileObj = request.FILES['file']
        fd = open('c:/test.txt', 'wb')
        fd.write(fileObj['content'])
        fd.close()

        form = PictureForm(request.POST, request.FILES)  
        #saveFileModel.save(form)
        #save_file("",request.FILES.get()['content'])
        #if form.is_valid():  
        f = request.FILES["file"]  
        des_origin_f = open("C:\\views.py","w")  
        #print des_origin_f
        for chunk in f.chunks():  
            des_origin_f.write(chunk)  
        des_origin_f.close()
        return HttpResponseRedirect('upfile')
    else:
        form = PictureForm()
    return render_to_response('upfile.html', {'form': form})

def save_file(request): 
    if request.method == 'POST':  
        mymodel = saveFileModel.objects.get(id=1)
        file_content = request.FILES['file']
        mymodel.data.save(request.FILES['file'].name, file_content)
        return HttpResponseRedirect('upfile')
    else:
        form = PictureForm()
    return render_to_response('upfile.html', {'form': form})

def upload_file(request):
    if request.method == 'POST':
        form = PictureForm(request.POST, request.FILES)
        #if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
        return HttpResponseRedirect('upfile')
    else:
        form = PictureForm()
    return render_to_response('upfile.html', {'form': form})

def handle_uploaded_file(f):
    destination = open('C:/JHL/WorkSpace/test.txt', 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()